package com.java1234.aspect;

import com.java1234.entity.SystemLogs;
import com.java1234.service.SystemLogsService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 系统日志切面类
 */
@Aspect
@Component
public class SystemLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    private SystemLogsService systemLogsService;

    @Pointcut("execution(* com.java1234.controller..*(..))")
    public void controllerMethods() {}

    @Before("controllerMethods()")
    public void logBefore(JoinPoint joinPoint) {
        logger.info("Logging Before: " + joinPoint.getSignature().getName() + "方法被调用");

        SystemLogs log = new SystemLogs();
        log.setMessage("调用了" + joinPoint.getSignature().getName() + "方法");
        log.setLevel("INFO");
        log.setLoggerName(joinPoint.getTarget().getClass().getName());
        log.setThreadName(Thread.currentThread().getName());
        log.setMethodName(joinPoint.getSignature().getName());
        log.setClassName(joinPoint.getTarget().getClass().getName());
        log.setCreateTime(new Date());

        systemLogsService.logSystem(log);
    }

    @AfterThrowing(pointcut = "controllerMethods()", throwing = "ex")
    public void logException(JoinPoint joinPoint, Throwable ex) {
        logger.error("Logging Exception in: " + joinPoint.getSignature().getName() + "方法", ex);

        SystemLogs log = new SystemLogs();
        log.setMessage("在" + joinPoint.getSignature().getName() + "方法中发生异常: " + ex.getMessage());
        log.setLevel("ERROR");
        log.setLoggerName(joinPoint.getTarget().getClass().getName());
        log.setThreadName(Thread.currentThread().getName());
        log.setMethodName(joinPoint.getSignature().getName());
        log.setClassName(joinPoint.getTarget().getClass().getName());
        log.setCreateTime(new Date());

        systemLogsService.logSystem(log);
    }
}